package com.jcfk.eam.service.main;

import com.jcfk.common.core.exception.CustomException;
import com.jcfk.eam.domain.dto.main.AssetChangeInfoDTO;
import com.jcfk.eam.domain.po.main.EamGrantRecordDetail;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.query.main.EamGrantRecordDetailQuery;
import com.jcfk.eam.domain.dto.main.EamGrantRecordDetailDTO;
import com.jcfk.eam.dao.main.EamGrantRecordDetailDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.eam.enums.AssetStatus;
import com.jcfk.eam.service.main.EamAssetInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import java.util.List;
import java.util.ArrayList;
import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.Date;

/**
 * 发放记录明细
 *
 * @author yql
 * @email 522891237@gqq.com
 * @date 2024-07-29
 */
@Service
public class EamGrantRecordDetailService extends BaseService<EamGrantRecordDetailDao,EamGrantRecordDetail> {

    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    /**
     * EamGrantRecordDetail分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamGrantRecordDetailDTO> queryByPage(DataPage<EamGrantRecordDetailDTO> page, EamGrantRecordDetailQuery query) {
        // 分页查询
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : query.getAssetName() + "%");
        query.setUsingDepartmentName(StringUtils.isEmpty(query.getUsingDepartmentName()) ? query.getUsingDepartmentName() : query.getUsingDepartmentName() + "%");
        query.setUsingPersonName(StringUtils.isEmpty(query.getUsingPersonName()) ? query.getUsingPersonName() : query.getUsingPersonName() + "%");
        query.setLocationBeforeGrant(StringUtils.isEmpty(query.getLocationBeforeGrant()) ? query.getLocationBeforeGrant() : query.getLocationBeforeGrant() + "%");
        query.setLocationAfterGrant(StringUtils.isEmpty(query.getLocationAfterGrant()) ? query.getLocationAfterGrant() : query.getLocationAfterGrant() + "%");
        query.setRepayPersonName(StringUtils.isEmpty(query.getRepayPersonName()) ? query.getRepayPersonName() : query.getRepayPersonName() + "%");
        query.setLocationAfterRepay(StringUtils.isEmpty(query.getLocationAfterRepay()) ? query.getLocationAfterRepay() : query.getLocationAfterRepay() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 判断EamGrantRecordDetail是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamGrantRecordDetailDTO dto) {
        QueryWrapper<EamGrantRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入发放记录明细
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamGrantRecordDetailDTO dto) {

        // 保存
        EamGrantRecordDetail item = new EamGrantRecordDetail();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新发放记录明细
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamGrantRecordDetailDTO dto) {
        // 保存
        EamGrantRecordDetail item = new EamGrantRecordDetail();
        BeanUtils.copyProperties(dto, item);
        // 默认数据
        this.setDefaultValue(item);

        //校验资产台账数据是否合法
        EamAssetInfo eamAssetInfo = eamAssetInfoService.getById(dto.getAssetId());
        if(eamAssetInfo == null || AssetStatus.EXERCISE.getValue() != eamAssetInfo.getAssetStatus() || eamAssetInfo.getDeleted() == 1){
            throw new CustomException("资产台账数据不合法，归还失败");
        }
        //更新资产台账数据
        AssetChangeInfoDTO assetChangeInfo=new AssetChangeInfoDTO();
//        assetChangeInfo.setUsingDepartmentId(null);
//        assetChangeInfo.setUsingDepartmentName(null);
//        assetChangeInfo.setUsingPersonId(null);
//        assetChangeInfo.setUsingPersonName(null);
        assetChangeInfo.setLocationId(dto.getLocationAfterRepayId());
        assetChangeInfo.setLocationName(dto.getLocationAfterRepay());
        assetChangeInfo.setAssetStatus(AssetStatus.STOCK.getValue());
        eamAssetInfoService.changeInfo(eamAssetInfo,assetChangeInfo);


        super.updateById(item);
    }

    /**
     * 根据批量主键删除发放记录明细(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamGrantRecordDetailDTO dto) {

        EamGrantRecordDetail item = new EamGrantRecordDetail();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamGrantRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamGrantRecordDetail item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取发放记录明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamGrantRecordDetailDTO get(String id) {
        // 查询数据
        EamGrantRecordDetail item = this.baseMapper.selectById(id);
        EamGrantRecordDetailDTO dto = new EamGrantRecordDetailDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 发放记录明细批量保存
     *
     * @param dtos
     * @return StandardCodeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<EamGrantRecordDetailDTO> dtos, String id) {
        List<EamGrantRecordDetail> insertList = new ArrayList<>();
        List<EamGrantRecordDetail> updateList = new ArrayList<>();
        List<String> notDeleteIds = new ArrayList<>();


        for (EamGrantRecordDetailDTO dto : dtos) {
            EamGrantRecordDetail item = new EamGrantRecordDetail();
            BeanUtils.copyProperties(dto, item);
            this.setDefaultValue(item);

            if (!StringUtils.isEmpty(dto.getId())) {
                notDeleteIds.add(dto.getId());
                updateList.add(item);
            } else {
                item.setIsRepay(0);
                insertList.add(item);
            }
        }

        // 删除
        QueryWrapper<EamGrantRecordDetail> queryWrapper = new QueryWrapper<>();
        if (notDeleteIds.size() > 0) queryWrapper.notIn("id", notDeleteIds);
        queryWrapper.lambda().eq(EamGrantRecordDetail::getRecordId, id);
        this.remove(queryWrapper);

        // 保存新增
        if (insertList.size() > 0) this.saveBatch(insertList);

        // 保存更新
        if (updateList.size() > 0) this.updateBigBatch(updateList);
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamGrantRecordDetailDTO>
     */
    public List<EamGrantRecordDetailDTO> getList(EamGrantRecordDetailQuery query) {
        // 查询条件
        QueryWrapper<EamGrantRecordDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getRecordId()), EamGrantRecordDetail::getRecordId, query.getRecordId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getSeq()), EamGrantRecordDetail::getSeq, query.getSeq());
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetId()), EamGrantRecordDetail::getAssetId, query.getAssetId());
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetCode()), EamGrantRecordDetail::getAssetCode, query.getAssetCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetName()), EamGrantRecordDetail::getAssetName, query.getAssetName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getUsingDepartmentId()), EamGrantRecordDetail::getUsingDepartmentId, query.getUsingDepartmentId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getUsingDepartmentName()), EamGrantRecordDetail::getUsingDepartmentName, query.getUsingDepartmentName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getUsingPersonId()), EamGrantRecordDetail::getUsingPersonId, query.getUsingPersonId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getUsingPersonName()), EamGrantRecordDetail::getUsingPersonName, query.getUsingPersonName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getLocationBeforeGrantId()), EamGrantRecordDetail::getLocationBeforeGrantId, query.getLocationBeforeGrantId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getLocationBeforeGrant()), EamGrantRecordDetail::getLocationBeforeGrant, query.getLocationBeforeGrant());
        qw.lambda().eq(!StrUtil.isEmpty(query.getLocationAfterGrantId()), EamGrantRecordDetail::getLocationAfterGrantId, query.getLocationAfterGrantId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getLocationAfterGrant()), EamGrantRecordDetail::getLocationAfterGrant, query.getLocationAfterGrant());
        qw.lambda().eq(query.getIsRepay() != null, EamGrantRecordDetail::getIsRepay, query.getIsRepay());
        qw.lambda().ge(!StrUtil.isEmpty(query.getRepayDateStart()), EamGrantRecordDetail::getRepayDate, query.getRepayDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getRepayDateEnd()), EamGrantRecordDetail::getRepayDate, query.getRepayDateEnd());
        qw.lambda().eq(!StrUtil.isEmpty(query.getRepayPersonId()), EamGrantRecordDetail::getRepayPersonId, query.getRepayPersonId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getRepayPersonName()), EamGrantRecordDetail::getRepayPersonName, query.getRepayPersonName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getLocationAfterRepayId()), EamGrantRecordDetail::getLocationAfterRepayId, query.getLocationAfterRepayId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getLocationAfterRepay()), EamGrantRecordDetail::getLocationAfterRepay, query.getLocationAfterRepay());
        qw.lambda().eq(query.getDeleted() != null, EamGrantRecordDetail::getDeleted, query.getDeleted());
        // 查询数据
        List<EamGrantRecordDetail> list = super.list(qw);

        return convertList(list, EamGrantRecordDetailDTO.class);
    }

    /**
     * 根据主键获取发放记录明细信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteitem(String id) {
        EamGrantRecordDetail item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }
}

